package com.lzb.compressmaster.utils;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import com.lzb.compressmaster.bean.RecentFileBean;
import com.lzb.compressmaster.basic.media.MediaInfo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class RecentFilesManager {
    
    private final Context context;
    
    public RecentFilesManager(Context context) {
        this.context = context;
    }
    
    /**
     * 获取最近7天内的所有媒体文件和下载文件，按日期分组
     */
    public List<RecentFileBean> getRecentFiles(int maxCount) {
        List<MediaInfo> allFiles = new ArrayList<>();
        
        // 获取最近图片
        allFiles.addAll(queryRecentImages());
        
        // 获取最近视频
        allFiles.addAll(queryRecentVideos());
        
        // 获取最近音频
        allFiles.addAll(queryRecentAudio());
        
        // 获取最近下载文件
        allFiles.addAll(queryRecentDownloads());
        
        // 按修改时间排序
        Collections.sort(allFiles, (f1, f2) -> Long.compare(f2.getDateModified(), f1.getDateModified()));
        
        // 限制总数量
        if (allFiles.size() > maxCount) {
            allFiles = allFiles.subList(0, maxCount);
        }
        
        // 按日期分组
        return groupFilesByDate(allFiles);
    }
    
    private List<RecentFileBean> groupFilesByDate(List<MediaInfo> files) {
        Map<String, RecentFileBean> dateGroups = new HashMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        
        for (MediaInfo file : files) {
            String dateStr = dateFormat.format(new Date(file.getDateModified()));
            
            if (!dateGroups.containsKey(dateStr)) {
                RecentFileBean bean = new RecentFileBean(dateStr, new ArrayList<>());
                dateGroups.put(dateStr, bean);
            }
            
            dateGroups.get(dateStr).getMediaInfoList().add(file);
        }
        
        // 将Map转换为List并按日期降序排序
        List<RecentFileBean> result = new ArrayList<>(dateGroups.values());
        Collections.sort(result, (b1, b2) -> b2.getTime().compareTo(b1.getTime()));
        
        return result;
    }
    
    private List<MediaInfo> queryRecentImages() {
        return queryMediaStore(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Images.Media.DATA,
                        MediaStore.Images.Media.DISPLAY_NAME,
                        MediaStore.Images.Media.DATE_MODIFIED
                },
                MediaStore.Images.Media.DATE_MODIFIED + " > " + (System.currentTimeMillis() / 1000 - 7 * 24 * 3600)
        );
    }
    
    private List<MediaInfo> queryRecentVideos() {
        return queryMediaStore(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Video.Media.DATA,
                        MediaStore.Video.Media.DISPLAY_NAME,
                        MediaStore.Video.Media.DATE_MODIFIED
                },
                MediaStore.Video.Media.DATE_MODIFIED + " > " + (System.currentTimeMillis() / 1000 - 7 * 24 * 3600)
        );
    }
    
    private List<MediaInfo> queryRecentAudio() {
        return queryMediaStore(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DISPLAY_NAME,
                        MediaStore.Audio.Media.DATE_MODIFIED
                },
                MediaStore.Audio.Media.DATE_MODIFIED + " > " + (System.currentTimeMillis() / 1000 - 7 * 24 * 3600)
        );
    }
    
    private List<MediaInfo> queryRecentDownloads() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return queryMediaStore(
                    MediaStore.Downloads.EXTERNAL_CONTENT_URI,
                    new String[]{
                            MediaStore.Downloads.DATA,
                            MediaStore.Downloads.DISPLAY_NAME,
                            MediaStore.Downloads.DATE_MODIFIED
                    },
                    MediaStore.Downloads.DATE_MODIFIED + " > " + (System.currentTimeMillis() / 1000 - 7 * 24 * 3600)
            );
        }
        return new ArrayList<>();
    }
    
    private List<MediaInfo> queryMediaStore(Uri uri, String[] projection, String selection) {
        List<MediaInfo> files = new ArrayList<>();
        
        try (Cursor cursor = context.getContentResolver().query(
                uri,
                projection,
                selection,
                null,
                MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC")) {
            
            if (cursor != null) {
                int dataIndex = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
                int nameIndex = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME);
                int dateIndex = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED);
                
                while (cursor.moveToNext()) {
                    String path = cursor.getString(dataIndex);
                    String name = cursor.getString(nameIndex);
                    long modified = cursor.getLong(dateIndex) * 1000L;
                    
                    if (path != null && new File(path).exists()) {
                        File file = new File(path);
                        MediaInfo mediaInfo = new MediaInfo(
                                path,
                                name,
                                file.length(),
                                modified,
                                null,
                                null
                        );
                        files.add(mediaInfo);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return files;
    }

}